package com.elasticsearchtemplate.dao;


import com.elasticsearchtemplate.entity.Emp;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Repository
public class EmpElasticTemplateDaoImpl implements EmpElasticTemplateDao {
    @Autowired
    private ElasticsearchRestTemplate template;

    @Override
    public List<Emp> findAllByName(String name) {
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("name", name))
                        .build();
        SearchHits<Emp> searchHits =  template.search(
                nativeSearchQuery, Emp.class);

        return searchHits.getSearchHits()
                .stream()
                .map(empSearchHit -> empSearchHit.getContent())
                .collect(Collectors.toList());
    }
}
